package com.bafa.front.events;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.bafa.debug.Debug;
import com.bafa.exceptions.TeamDoesNotExistException;
import com.bafa.jdbc.DBAccess;
import com.bafa.objects.Message;
import com.bafa.objects.PageBean;
import com.bafa.objects.team.Team;
import com.bafa.services.AdminServices;
import com.bafa.services.RetrieveServices;

public class UpdateAccountsEvent extends Event {

	@Override
	public void doEvent(HttpServletRequest request,
			HttpServletResponse response, PageBean page) {
		Debug.debug(this.getClass(),"doEvent","Entering....... ");
			
//			 Create a factory for disk-based file items
	        FileItemFactory factory = new DiskFileItemFactory();
			
	        // Create a new file upload handler
	        ServletFileUpload upload = new ServletFileUpload(factory);
			Debug.debug(this.getClass(),"doEvent","We've uploaded");
			try{
				// Parse the request
				List items = upload.parseRequest(request);
				Debug.debug(this.getClass(),"doEvent","List size is "+items.size());
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (!item.isFormField()) {
						if(item.getName().indexOf("xls")<1){
				               Debug.debug(this.getClass(),"doEvent"," This is not a valid file");
				        }else{
				        	try{
								Debug.debug(this.getClass(),"doEvent","We're starting out");
								InputStream uploadedStream = item.getInputStream();
	        					POIFSFileSystem fs = new POIFSFileSystem(uploadedStream);
	                 			HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
	                                                
	                            /*******************Get Accounts Sheet*************************/
	                            HSSFSheet teams = hssfworkbook.getSheetAt(0);
								
								int rows  = teams.getPhysicalNumberOfRows();
								Debug.debug(this.getClass(),"doEvent","We're starting out");
	                            HashMap addedTeams = new HashMap();
	                            for (int r = 1; r < rows; r++)
	                            {
									String team = "";
								try{
									HSSFRow row   = teams.getRow(r);
	                               team = row.getCell((short)0).getRichStringCellValue().getString();
								   Team teamObj = RetrieveServices.getTeamByName(team.trim());
								   int teamId = teamObj.getId();
								   float totalbeforediscounts=0;
								   if(row.getCell((short)2)!=null)
									   totalbeforediscounts = (float)row.getCell((short)2).getNumericCellValue();
								   float discounts = 0;
								   if(row.getCell((short)3)!=null)
									   discounts = (float)row.getCell((short)3).getNumericCellValue();
								   float fines = 0;
								   if(row.getCell((short)4)!=null)
									   fines = (float)row.getCell((short)4).getNumericCellValue();
								   String comment ="";
								   if(row.getCell((short)6)!=null)
									   comment = row.getCell((short)6).getRichStringCellValue().getString();
								   
								   Message adminMessage = AdminServices.updateMoneyOwed(teamId,new Double(totalbeforediscounts-discounts+fines));
								   
								   DBAccess db = new DBAccess();
								   db.updateAccounts(teamId,totalbeforediscounts,discounts,fines,comment);
								   message.addAllMessages(adminMessage);
								} catch (TeamDoesNotExistException teamNotExist) {
									message
											.addError(teamNotExist
													.getTeamName()
													+ " does not exist and could not be updated");
								}catch (Exception e){
									message.addError("Error with updating the accounts of "+team);
									Debug.printStackTrace(e);
								}
							
	                            }
								
				        	}catch(Exception e){
								Debug.printStackTrace(e);
				        	}
				        }
					}
				}
			}catch(Exception e){
				Debug.printStackTrace(e);
			}

		}


}
